import { ref, type Ref } from "vue";
import { getOpenMarker } from "@/api/markerApi";
import { findOpenJournal } from "@/api/journalApi";
import { ResponseCode } from "@/common/Responsetypes";
import type { AMapCustomExposed } from "@/components/amapCustom/types";
import { useMarkerStore } from "@/stores/useMarkerStore";
import type { IJournalOmit } from "@/components/journalList/journalList.vue";
import type { IUvPopup } from "@/common/UvTypes";
import type { IPopupFlexExposed } from "@/components/popupFlex/types";
import _ from "lodash-es";

export default function (
  mapRef: Ref<AMapCustomExposed | null>,
  popup: Ref<IUvPopup | null>,
  popupFlexRef: Ref<IPopupFlexExposed | null>
) {
  /**
   * 搜索关键字
   */
  const searchKeyRef = ref<string>("");

  const openJournalsRef = ref<IJournalOmit[]>([]);

  const { state } = useMarkerStore();

  const handleSearch = _.debounce(function () {
    if (!searchKeyRef.value) return;

    if (Number.isNaN(searchKeyRef.value)) {
      uni.showToast({
        title: "请输入数字",
        icon: "none",
      });
    } else {
      uni.showLoading();
      getOpenMarker(Number(searchKeyRef.value)).then((res) => {
        // 清空地图上的 用户marker
        if (res.code === ResponseCode.PASS) {
          uni.hideLoading();
          if (res.data.length === 0) {
            uni.showToast({
              title: "没有任何旅游地点",
              mask: true,
              icon: "none",
            });
            return;
          }
          mapRef.value!.clearMarkers();
          popup.value?.close();
          res.data.forEach((item) => {
            mapRef.value!.addMarkerToMap(item, {
              onClick(event) {
                if (state.activeMarkerExtra) {
                  state.activeMarkerExtra.setActive(false);
                }
                state.activeMarkerExtra = event;
                event.setActive(true);
                uni.showLoading({});
                // 获取 当前 marker 的 公开日记
                findOpenJournal(item.m_id, item.u_id).then((res) => {
                  if (res.code === ResponseCode.PASS) {
                    uni.hideLoading();
                    if (res.data.length === 0) {
                      uni.showToast({
                        title: "没有任何日记",
                        icon: "none",
                      });
                    } else {
                      openJournalsRef.value = res.data;
                      popupFlexRef.value?.open();
                    }
                  }
                });
              },
            });

            mapRef.value!.setFitView();
          });
        }
      });
    }
  }, 500);

  return {
    searchKeyRef,
    handleSearch,
    openJournalsRef,
  };
}
